package com.rtline.business.config;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

@Configuration
public class DataSourceConfig {

    @Bean(name = "masterDataSource")
    //此配置先隐藏，读取此配置生成DataSource时，无法获取到jdbc-url属性。暂时写为手动填充
    // @ConfigurationProperties(prefix = "spring.datasource.dynamic.datasource.master")
    // return new HikariDataSource();
    public DataSource masterDataSource() {
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl("jdbc:mysql://localhost:3306/business_rt?useSSL=false&serverTimezone=UTC");
        config.setUsername("root");
        config.setPassword("password");
        config.setDriverClassName("com.mysql.cj.jdbc.Driver");
        return new HikariDataSource(config);
    }

    @Bean(name = "slaveDataSource")
    //此配置先隐藏，读取此配置生成DataSource时，无法获取到jdbc-url属性。暂时写为手动填充
    // @ConfigurationProperties(prefix = "spring.datasource.dynamic.datasource.slave")
    public DataSource slaveDataSource() {
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl("jdbc:mysql://localhost:3306/business_slave?useSSL=false&serverTimezone=UTC");
        config.setUsername("root");
        config.setPassword("password");
        config.setDriverClassName("com.mysql.cj.jdbc.Driver");
        return new HikariDataSource(config);
    }

    @Bean
    public DynamicDataSourceProvider dynamicDataSourceProvider(@Qualifier("masterDataSource") DataSource masterDataSource,
                                                               @Qualifier("slaveDataSource") DataSource slaveDataSource) {
        Map<String, DataSource> dataSourceMap = new HashMap<>();
        dataSourceMap.put("master", masterDataSource);

        dataSourceMap.put("slave", slaveDataSource);
        return () -> dataSourceMap;
    }

    @Bean
    @Primary
    public DataSource dynamicDataSource(DynamicDataSourceProvider dynamicDataSourceProvider) {
        return new DynamicRoutingDataSource(List.of(dynamicDataSourceProvider));
    }
}
